package com.exam.demo.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exam.demo.entity.Paper;
import com.exam.demo.mapper.PaperMapper;
import com.exam.demo.service.PaperService;
import com.exam.demo.util.NameMap;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 功能描述
 *
 * @author yxj30
 * @date 2022/03/16  19:29
 */
@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

    @Resource
    PaperMapper paperMapper;

    @Override
    public HttpServletResponse export(HttpServletResponse response) throws IOException {
        // 从数据库查询出所有的数据
        List<Paper> list = list();//paperService.list
        System.out.println(list);
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //重点： 自定义标题别名
        Map<String, String> nameMap = NameMap.getPaperNameMap();

        Set<String> keySet = nameMap.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            writer.addHeaderAlias(key, nameMap.get(key));
        }


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("管理员信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
        return response;
    }

    /**
     * 导入数据库
     *
     * @param file
     * @return
     */
    @Override
    public boolean imp(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //1.读取xlsx数据
        List<Map<String, Object>> readAll = reader.readAll();

        //2.替换表头
        Map<String, String> nameMap = NameMap.getPaperNameMap();
        List<Paper> papers = new LinkedList<>();//存储替换后的paper
        for (Map paperMap :
                readAll) {
            Iterator<Map.Entry<String, Object>> iterator = paperMap.entrySet().iterator();
            Map<String, Object> newPaperMap = new LinkedHashMap<>();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                String key = NameMap.getKey(nameMap, entry.getKey());
                if(key == null){
                    return false;
                }
                if (key == "id") {
                    newPaperMap.put(key, null);
                } else {
                    newPaperMap.put(key, entry.getValue());
                }
            }
            System.out.println(newPaperMap);
            Paper paper = JSON.parseObject(JSON.toJSONString(newPaperMap), Paper.class);
            papers.add(paper);
        }
        System.out.println(papers);
        //3.批量插入数据
        boolean b = saveBatch(papers);
        return b;
    }

    @Override
    public Page<Paper> findPage(Page<Paper> paperPage, String paperName,String teacherId) {
        return paperMapper.findPage(paperPage,paperName,teacherId);
    }

}
